<template>
  <div class="wrapper">
    <div class="actions" style="margin-bottom: 10px">
      <div class="left">
        <el-button type="primary" plain size="mini" @click="handleClickExport"
          >导出</el-button
        >
      </div>
    </div>
    <div style="width: 100%">
      <!--  show-summary :summary-method="getSummaries" -->
      <el-table
        :default-sort="sortRule"
        ref="table"
        @sort-change="sortChange"
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :max-height="maxheight"
      >
        <!-- <el-table-column type="selection" width="45"> </el-table-column> -->
        <el-table-column
          prop=""
          label="序号"
          width="50"
          type="index"
        ></el-table-column>
        <el-table-column
          sortable="custom"
          width="120px"
          v-for="(item, index) in headerData"
          :key="index"
          :prop="item.show_name"
          :label="item.title"
          :align="item.align"
        >
        </el-table-column>
        <el-table-column prop=""> </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import {
  CustomChartOption,
  CustomSubChartOption,
  CustomSubChartShow,
} from "@/api/report";
import { commonAdd } from "@/utils/mUtils";

export default {
  name: "reportTable",
  components: {},
  props: ["searchParams", "tableKey"],
  data() {
    return {
      maxheight: "auto",
      loading: false,
      tableData: [],
      headerData: [],
      oldData: [],
      sortRule: {
        prop: null,
        order: null,
      },
    };
  },
  //   watch: {
  //     tableKey: {
  //       handler(newValue, oldValue) {

  //         // console.log("tab变化了");
  //       },
  //       immediate: true,
  //     },
  //   },
  mounted() {},
  methods: {
    getCharts(params) {
      // console.log("getCharts exec", params);
      this.loading = true;

      CustomSubChartShow({
        id: this.tableKey,
        ...params,
      }).then((res1) => {
        if ((res1 || {}).code === 10000) {
          this.tableData = res1.data.data;
          if (this.tableData.length > 6) {
            //两排操作栏
            this.maxheight = document.documentElement.clientHeight - 250;
          } else {
            this.maxheight = "auto";
          }
          this.headerData = res1.data.item_list;
          this.loading = false;
        } else {
          this.tableData = [];
          this.headerData = [];
          this.loading = false;
        }
        this.afterCrudRefresh();
      });
    },
    handleClickExport() {
      this.$emit("export", this.tableKey);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        const values = data.map((item) => item[column.property]);
        let sum = 0;
        // console.log(values);
        const isNumber = values.every(
          (item) => (item && this.isNumber(item)) || item == ""
        );
        const isEmpty = values.every((item) => item == undefined || item == "");

        const isPercent = values.every(
          (item) => (item && item.indexOf("%") > 0) || item == ""
        );
        values.forEach(function (item, index) {
          if (item == null) {
            item = 0;
          }
          if (typeof item == "string" && item.indexOf("%") > 0) {
            item = Number(item.split("%")[0]);
          }
          // var aaa = Number(item);
          if (!isNaN(aaa)) {
            sum = commonAdd(sum, Number(item));
          } else {
            sum = null;
          }
        });
        // console.log(sum);
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (isEmpty) {
          sums[index] = "";
          return;
        }
        if (isNumber) {
          if (isPercent) {
            sums[index] = sum + "%";
            return;
          } else {
            sums[index] = sum;
            return;
          }
        } else {
          sums[index] = "";
          return;
        }
        // if (index === 0) {
        //   sums[index] = '合计';
        //   return;
        // }
        // if (index === 1) {
        //   sums[index] = '';
        //   return;
        // }
        // if (index === 2) {
        //   sums[index] = sum;
        //   return;
        // }
        // if (index === 3) {
        //   sums[index] = sum;
        //   return;
        // }
        // if (index === 4) {
        //   sums[index] = sum + "%";
        //   return;
        // }
        // if (index === 5) {
        //   sums[index] = sum + "%";
        //   return;
        // }
        // if (index === 6) {
        //   sums[index] = sum;
        //   return;
        // }
      });

      return sums;
    },
    afterCrudRefresh() {
      // 不能直接用=号赋值，避免this.oldData 与 this.tableData 指向同一个地址
      if (this.tableData.length > 0) {
        this.oldData.length = 0;
        this.tableData.forEach((item) => {
          this.oldData.push(item);
        });
      }
      // 点击下一页或者翻页后清除排序
      if (this.$refs.table) this.$refs.table.clearSort();
    },
    // 自定义排序
    sortChange(column) {
      const prop = column.prop;
      if (prop) {
        this.proptype = prop;
        const isNumber = this.tableData.every((item) => {
          return (
            this.isNumber(item[this.proptype]) || item[this.proptype] == ""
          );
        });
        // console.log(isNumber, "isNumber==========------==============");

        if (column.order === "ascending") {
          const first = this.tableData.shift();
          this.tableData = this.tableData.sort((a, b) =>
            this.ascSortFun(a, b, isNumber)
          );
          this.tableData.unshift(first);
        } else if (column.order === "descending") {
          const first = this.tableData.shift();
          this.tableData = this.tableData.sort((a, b) =>
            this.desSortFun(a, b, isNumber)
          );
          this.tableData.unshift(first);
        } else {
          // 再点击向上【向下】恢复原始排序
          this.tableData.length = 0;
          this.oldData.forEach((item) => {
            this.tableData.push(item);
          });
        }
      }
    },
    // 升序排列方法
    ascSortFun(a, b, isNumber) {
      if (!isNumber) {
        const aLength = a[this.proptype] === null ? 0 : a[this.proptype].length;
        const bLength = b[this.proptype] === null ? 0 : b[this.proptype].length;
        // console.log("not number", aLength - bLength);
        return aLength - bLength;
      } else {
        // console.log(
        //   parseFloat(a[this.proptype] || 0),
        //   parseFloat(b[this.proptype] || "0"),
        //   parseFloat(a[this.proptype] || "0") -
        //     parseFloat(b[this.proptype] || "0")
        // );
        return (
          parseFloat(a[this.proptype] || "-1") -
          parseFloat(b[this.proptype] || "-1")
        );
      }
    },
    // 降序排列方法
    desSortFun(a, b, isNumber) {
      if (!isNumber) {
        const bLength = b[this.proptype] === null ? 0 : b[this.proptype].length;
        const aLength = a[this.proptype] === null ? 0 : a[this.proptype].length;
        // console.log("not number", bLength - aLength);

        return bLength - aLength;
      } else {
        // console.log(
        //   parseFloat(b[this.proptype] || 0),
        //   parseFloat(a[this.proptype] || 0),
        //   parseFloat(b[this.proptype] || 0) - parseFloat(a[this.proptype] || 0)
        // );

        return (
          parseFloat(b[this.proptype] || -1) -
          parseFloat(a[this.proptype] || -1)
        );
      }
    },
    // 校验只要是数字（包含正负整数，0以及正负浮点数）就返回true
    isNumber(val) {
      var regPos = /^\d+(\.\d+)?$/; // 非负浮点数
      var regNeg =
        /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
      var regPercent = new RegExp(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/);
      if (regPos.test(val) || regNeg.test(val) || regPercent.test(val)) {
        // console.log("1111111111");
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  .actions {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: 100%;
    background-color: #fff;

    .el-button + .el-dropdown,
    .el-dropdown + .el-button {
      margin-left: 10px;
    }
  }

  /deep/.el-table {
    display: grid;
  }

  /deep/ .el-table__body-wrapper {
    order: 1;
  }
}
</style>